package com.web.visitors_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.web.visitors_backend.mapper.VisitorMapper;
import com.web.visitors_backend.model.Visitor;
import com.web.visitors_backend.model.VisitorVO;
import com.web.visitors_backend.service.VisitorService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 86139
 * @description 针对表【visitor】的数据库操作Service实现
 * @createDate 2025-05-13 15:22:47
 */
@Service
public class VisitorServiceImpl extends ServiceImpl<VisitorMapper, Visitor>
        implements VisitorService {

    @Override
    public List<VisitorVO> getVisitorsFromDateRange(Date startTime, Date endTime) {
        Page<Visitor> page = new Page<>(1,1000);
        LambdaQueryWrapper<Visitor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(Visitor::getTime, startTime)
                .le(Visitor::getTime, endTime).orderByDesc(Visitor::getTime);
        IPage<Visitor> iPage = this.page(page, queryWrapper);
        return iPage.getRecords().stream().map(this::getVisitorVO).collect(Collectors.toList());
    }

    @Override
    public List<VisitorVO> getAllVisitors() {
        Page<Visitor> page = new Page<>(1, 100);
        QueryWrapper<Visitor> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Visitor::getName, "cxx123").orderByDesc(Visitor::getTime);
        IPage<Visitor> iPage = this.page(page, queryWrapper);
        return iPage.getRecords().stream().map(this::getVisitorVO).collect(Collectors.toList());
    }


    @Override
    public VisitorVO getVisitorVO(Visitor visitor) {
        VisitorVO visitorVO = new VisitorVO();
        BeanUtils.copyProperties(visitor, visitorVO);
        // 创建一个 SimpleDateFormat 对象，并指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        // 使用 SimpleDateFormat 对象将 Date 对象格式化为字符串
        String formattedDate = sdf.format(visitor.getTime());
        visitorVO.setTime(formattedDate);
        return visitorVO;
    }

}




